const User = require('../models/user');
const path = require('path');
//操作符
const {Op} = require('sequelize');
const jsonwebtoken = require('jsonwebtoken');
const {secret} = require('../config/index');
const moment = require('moment');
class UsersCtl{
  //获取用户列表
  async find(ctx){
    const currentPage = ctx.request.query.currentPage
    //可显示的不敏感的字段
    const someAttributes = ['user_id','username','learnDay','create_time'];
    const {count,rows} = await User.findAndCountAll({
      attributes:someAttributes,
      order:[
        ['learnDay','DESC']
      ],
      limit:  10,
      offset: (currentPage - 1) * 10
    });
    ctx.body = {
      status:200,
      msg:'success',
      data:{
        count,
        data:rows
      }
    }
  }
  //获取特定用户
  async findById(ctx){
    //SELECT * FROM user id = ${ctx.params.id}
    const user = await User.findOne({
      where:{
        user_id:ctx.params.id
      }
    });
    //用户不存在
    if(!user){ ctx.throw(404,'用户不存在');}
    ctx.body = user; //用户不存在
  }
  //创建用户
  async create(ctx){
    //校验请求体的name位字符串类型并且是必选的
    ctx.verifyParams({
      username:{ type:'string',required:true },
      password:{type:'string',required:true },
    });
    //获取请求体中的用户名
    const { username } = ctx.request.body;
    //findOne返回符合条件的第一个用户
    const repeatedUser = await User.findOne({
      where:{
          username:username
      }
    });
    //如果有重复用户返回409状态码代表冲突
    if(repeatedUser){
      ctx.throw(409,"用户名已被占用");
    }
    await User.create({
      username:username,
      password:ctx.request.body.password
    })
    ctx.body = {
      status:200,
      msg:'注册成功'
    };
  }
  //修改密码
  async updatePassword(ctx){
    const {newpwd} = ctx.request.body;
      await User.update({
        password:newpwd
      },{
        where:{
            user_id:ctx.state.user.user_id,
  
        }
      })
      ctx.body = {
        status:200,
        msg:'修改成功'
      }
    }
    
  //删除用户
  async delete(ctx){
    const user = await User.findOne({
      where:{
        user_id:ctx.params.id
      }
    });
    if(!user){ctx.throw(404,'用户不存在');}
    await user.destroy();
    ctx.body = {
      status:204,
      msg:'删除该用户成功'
    }
  }
  //登录
  async login(ctx){
    ctx.verifyParams({
      username:{type:'string',required:true},
      password:{type:'string',required:true},
    });

    //登录有两种情况：用户名不存在或密码错误，登录失败；登录成功
    //查找符合条件的第一个用户
    const user = await User.findOne({
      where:{
        [Op.and]:{
          username:ctx.request.body.username,
          password:ctx.request.body.password
        }
      }
    });
    if(!user){ctx.throw(401,'用户名或密码不正确！');}
    //获取id和username
    const {user_id,username} = user;
    const token = jsonwebtoken.sign({user_id,username},secret,{expiresIn:'1d'});
    ctx.body = {
      status:200,
      data:{
        token,
        user
      }
    };
  }
  //打卡签到
  async clockIn(ctx){
    const user_id = ctx.state.user.user_id;
    await User.findByPk(user_id).then(function(user){
      //获取请求打卡时间
      const nowTime = moment().format('YYYY-MM-DD');
      const recentTime = moment(user.get('updatedAt')).format('YYYY-MM-DD');
      if(nowTime === recentTime){
        ctx.body = {
          status:403,
          msg:'今天已经打过卡了'
        }
      }else{
        user.increment('learnDay')
        ctx.body = {
          status:200,
          msg:'打卡成功'
        }
      }
    })
    
  }
}
module.exports = new UsersCtl();